import java.util.ArrayList;
import java.util.Stack;


public class Calculate {
    public Integer getValue() {
        return value;
    }

    private Integer value;

    public Calculate(IntegerExpression exp) {
        ArrayList strList = getStringList(exp.toString());
        ArrayList rpn = getRPN(strList);
        value = calculate(rpn);
    }

    private ArrayList<String> getStringList(String str) {
        ArrayList<String> result = new ArrayList<String>();
        String num = "";
        for (String item : str.split(" ")) result.add(item);
        return result;
    }

    //求逆波兰表达式
    private ArrayList<String> getRPN(ArrayList<String> inOrderList) {
        ArrayList<String> RPN = new ArrayList<String>();
        Stack<String> stack = new Stack<String>();
        for (String item : inOrderList) {
            if (Character.isDigit(item.charAt(0))) RPN.add(item);
            else {
                while (!stack.isEmpty() && compare(stack.peek(), item)) RPN.add(stack.pop());
                stack.push(item);
            }
        }
        while (!stack.isEmpty()) RPN.add(stack.pop());
        return RPN;
    }

    //计算后缀表达式 
    private Integer calculate(ArrayList<String> RPN) {
        Stack stack = new Stack();
        for (String item : RPN) {
            if (Character.isDigit(item.charAt(0))) stack.push(Integer.parseInt(item));
            else {
                Integer back = (Integer) stack.pop();
                Integer front = (Integer) stack.pop();
                Integer res = 0;
                switch (item.charAt(0)) {
                    case '+': {
                        res = front + back;
                        break;
                    }
                    case '-': {
                        res = front - back;
                        break;
                    }
                    case '*': {
                        res = front * back;
                        break;
                    }
                    case '/': {
                        res = front / back;
                        break;
                    }
                }
                stack.push(res);
            }
        }
        return (Integer) stack.pop();
    }

    //比较运算符等级 
    private static boolean compare(String peek, String cur) {
        if ("*".equals(peek) && ("/".equals(cur) || "*".equals(cur) || "+".equals(cur) || "-".equals(cur))) {
            return true;
        } else if ("/".equals(peek) && ("/".equals(cur) || "*".equals(cur) || "+".equals(cur) || "-".equals(cur))) {
            return true;
        } else if ("+".equals(peek) && ("+".equals(cur) || "-".equals(cur))) {
            return true;
        } else if ("-".equals(peek) && ("+".equals(cur) || "-".equals(cur))) {
            return true;
        }
        return false;
    }
}
